<?php


namespace app\common\caches;


use Carbon\Carbon;
use think\facade\Cache;

class WechatCache
{
    /**
     * @todo 初始化微信打款限流器，30/s
     * @see https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
     * @return bool
     */
    public static function initPayToBalanceLimit()
    {
        $limiter = [
            'limit' => 30,
            'micro_time' => Carbon::now()->getPreciseTimestamp(3)   //当前毫秒数
        ];
        return Cache::store('redis')->handler()->hmset('pay.to.balance.limit', $limiter);
    }

    /**
     * @todo 获取微信支付限流器
     * @return mixed
     */
    public static function getPayToBalanceLimit()
    {
        // 不存在key
        if (!Cache::store('redis')->handler()->exists('pay.to.balance.limit')){
            self::initPayToBalanceLimit();
        }
        return Cache::store('redis')->handler()->hmget('pay.to.balance.limit', ['limit', 'micro_time']);
    }

    /**
     * @todo 微信支付限流器自减
     * @return false|int
     */
    public static function decPayToBalanceLimit()
    {
        return Cache::store('redis')->handler()->hincrby('pay.to.balance.limit', 'limit', -1);
    }
}
